package com.haitaoit.chengquan.module.home.activity.maintenance;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.car.activity.OrderPayActivity;
import com.haitaoit.chengquan.module.center.activity.info.MyAddressActivity;
import com.haitaoit.chengquan.module.center.activity.xuqiu.PaySuccessActivity;
import com.haitaoit.chengquan.module.home.model.ServerOrderModel;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.pickerview.TimeChegePopupWindow;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ServerOrderActivity extends BaseActivity {
    @ViewInject(R.id.order_addresstv)
    TextView     order_addresstv;
    @ViewInject(R.id.address_ll)
    LinearLayout address_ll;
    @ViewInject(R.id.title_img)
    ImageView    title_img;
    @ViewInject(R.id.fuwu_time)
    TextView     fuwu_time;
    @ViewInject(R.id.address_name)
    TextView     address_name;
    @ViewInject(R.id.address_address)
    TextView     address_address;
    @ViewInject(R.id.address_phone)
    TextView     address_phone;
    @ViewInject(R.id.server_title)
    TextView     server_title;
    @ViewInject(R.id.describe)
    TextView     describe;
    @ViewInject(R.id.reference_price)
    TextView     reference_price;
    @ViewInject(R.id.price_num)
    TextView     price_num;
    @ViewInject(R.id.price_zonji)
    TextView     price_zonji;
    @ViewInject(R.id.user_remark)
    TextView     user_remark;
    @ViewInject(R.id.price_and)
    TextView     price_and;


    private String           service_id;
    private ServerOrderModel model;
    private String           mStartTime;
    private String           mEndTime;
    private String           seven;
    private String mFuwuseven;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_server_order);
        setTitle_V("确认订单");
        setLeftShow(1, R.mipmap.left);
        backLeft_V();
        ViewUtils.inject(this);
        service_id = getIntent().getStringExtra("id");
        seven = getIntent().getStringExtra("seven");
        if (seven!=null){
            price_and.setText("价格范围");
        }
        mFuwuseven = getIntent().getStringExtra("fuwuseven");

    }

    @Override
    protected void onResume() {
        httpGetconfirm_service_order();
        super.onResume();
    }

    @OnClick({R.id.address_ll, R.id.fuwu_time, R.id.order_submit, R.id.order_addresstv})
    public void onClick(View v) {// 收起键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.address_ll:// 地址
                intent.setClass(this, MyAddressActivity.class);
                startActivity(intent);
                break;
            case R.id.fuwu_time:
                TimeChegePopupWindow startTime = new TimeChegePopupWindow(this, TimeChegePopupWindow.Type.ALL);
                startTime.setTime(new Date());// 时间选择后回调
                startTime.setOnTimeSelectListener(new TimeChegePopupWindow.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date) {
                        StringBuffer buffer = new StringBuffer();

                        String time = getTime(date);
                        String year = getYear(date);
                        String[] split = time.split("—");
                        String hand = split[0];
                        String last = split[1];
                        String substring = hand.substring(hand.length() - 2, hand.length());
                        if (substring.contains("-")) {
                            substring = hand.substring(hand.length() - 1, hand.length());
                        }
                        if (Integer.parseInt(substring) > Integer.parseInt(last)) {
                            ToastUtils.showToast("选择时间必须合理");
                            fuwu_time.setText("");
                            return;
                        }
                        mStartTime = hand + ":00";
                        mEndTime = year + last + "  :00";
                        buffer.append(hand).append(":00").append("—").append(last).append(":00");
                        fuwu_time.setText(buffer.toString());
                    }
                });
                startTime.showAtLocation(fuwu_time, Gravity.BOTTOM, 0, 0, new Date());
                break;

                //提交订单
            case R.id.order_submit:
                if (model.getMoren_model() == null) {
                    ToastUtils.showToast("请选择地址！");
                } else if (fuwu_time.getText().toString().trim().equals("")) {
                    ToastUtils.showToast("请选择服务时间！");
                } else {
                    httpGetadd_service_order();
                }
                break;
            case R.id.order_addresstv:// 地址
                intent.setClass(this, MyAddressActivity.class);
                startActivity(intent);
                break;
        }
        super.onClick(v);
    }

    // 得详情
    private void httpGetconfirm_service_order() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("service_id", service_id));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("service_id", service_id);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getconfirm_service_order, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            break;
                        case 0:// 成功
                            model = gson.fromJson(Response, ServerOrderModel.class);
                            if (model.getMoren_model() == null) {
                                order_addresstv.setVisibility(View.VISIBLE);
                                address_ll.setVisibility(View.GONE);
                            } else {
                                order_addresstv.setVisibility(View.GONE);
                                address_ll.setVisibility(View.VISIBLE);
                                address_name.setText("联系人：" + model.getMoren_model().getName());
                                address_phone.setText(model.getMoren_model().getPhone());
                                address_address.setText("服务地址：" + model.getMoren_model().getAddress());
                            }
                            ImageLoader.getInstance().displayImage(model.getTitle_img(), title_img);
                            server_title.setText(model.getTitle());
                            describe.setText(model.getDescribe());
                            if (model.getType().equals("7")) {
                                reference_price.setText("¥ " + model.getReference_price_low() + "～¥ " + model.getReference_price_high());
                                price_num.setText("¥ " + model.getReference_price_low() + "～¥ " + model.getReference_price_high());
                                price_zonji.setText("¥ " + model.getReference_price_low() + "～¥ " + model.getReference_price_high());
                            } else {
                                reference_price.setText("¥ " + model.getReference_price_low());
                                price_num.setText("¥ " + model.getReference_price_low());
                                price_zonji.setText("¥ " + model.getReference_price_low());
                            }
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 提交
    private void httpGetadd_service_order() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("service_id", service_id));
        list.add(new NameValuePairSign("address_id", model.getMoren_model().getAddress_id()));
        list.add(new NameValuePairSign("user_remark", user_remark.getText().toString()));
        list.add(new NameValuePairSign("service_endtime", mEndTime));
        list.add(new NameValuePairSign("service_time", mStartTime));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("service_id", service_id);
        params.addQueryStringParameter("address_id", model.getMoren_model().getAddress_id());
        params.addQueryStringParameter("user_remark", user_remark.getText().toString());
        params.addQueryStringParameter("service_time", mStartTime);
        params.addQueryStringParameter("service_endtime", mEndTime);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getadd_service_order, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            break;
                        case 0:// 成功
                            JSONObject js = new JSONObject(Response);
                            if (js.getString("type").equals("7")) {
                                Intent intent = new Intent(ServerOrderActivity.this, PaySuccessActivity.class);
                                intent.putExtra("type", "xiuqiu_order");
                                startActivity(intent);
                                finish();
                            } else {
                                Intent intent = new Intent(ServerOrderActivity.this, OrderPayActivity.class);
                                intent.putExtra("order_no", js.getString("order_no"));
                                intent.putExtra("order_amount", js.getString("order_amount"));
                                if (mFuwuseven!=null){
                                    intent.putExtra("fuwuseven", "fuwuseven");
                                }
                                startActivity(intent);
                                finish();
                            }
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    /**
     * 日期格式
     *
     * @param date
     * @return
     */
    public static String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd   HH—mm");
        return format.format(date);
    }

    public static String getYear(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);

    }
}
